import sys
import os
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                             QHBoxLayout, QLabel, QPushButton, QTableWidget, 
                             QTableWidgetItem, QHeaderView, QFrame, QFileDialog,
                             QMessageBox, QStyledItemDelegate, QMenu, QInputDialog)
from PyQt6.QtCore import Qt, QSize, QMarginsF
from PyQt6.QtGui import QFont, QPalette, QColor, QIcon, QTextDocument, QPageSize, QPageLayout
from PyQt6.QtPrintSupport import QPrinter

class WrapTextDelegate(QStyledItemDelegate):
    """自定义委托类，支持文本换行"""
    def paint(self, painter, option, index):
        text = index.data(Qt.ItemDataRole.DisplayRole)
        if text and '\n' in text:
            # 绘制多行文本
            painter.save()
            painter.setClipRect(option.rect)
            
            # 设置字体
            font = painter.font()
            painter.setFont(font)
            
            # 计算文本区域
            text_rect = option.rect.adjusted(4, 4, -4, -4)
            
            # 绘制文本
            painter.drawText(text_rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, text)
            
            painter.restore()
        else:
            # 使用默认绘制
            super().paint(painter, option, index)

class EditableDelegate(QStyledItemDelegate):
    """自定义委托类，控制哪些列可编辑"""
    def __init__(self, editable_columns, parent=None):
        super().__init__(parent)
        self.editable_columns = editable_columns
    
    def createEditor(self, parent, option, index):
        # 只有在可编辑列中才创建编辑器
        if index.column() in self.editable_columns:
            return super().createEditor(parent, option, index)
        return None

class EbbinghausVocabularyApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.word_banks = {}  # 存储单词库
        self.load_word_banks()
        self.init_ui()
        self.load_vocabulary()
        
    def init_ui(self):
        self.setWindowTitle("Ebbinghaus Vocabulary List")
        self.setGeometry(100, 100, 1200, 800)
        
        # 设置主窗口背景色
        self.setStyleSheet("""
            QMainWindow {
                background-color: #f5f5f5;
            }
        """)
        
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(10)
        
        # 创建按钮区域
        self.create_buttons(main_layout)
        
        # 创建表格区域
        self.create_table(main_layout)
        
    def create_buttons(self, parent_layout):
        """创建按钮区域"""
        button_layout = QHBoxLayout()
        
        # 导出PDF按钮
        export_button = QPushButton("导出PDF")
        export_button.setStyleSheet("""
            QPushButton {
                background-color: #1976d2;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 10px 20px;
                font-size: 14px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #1565c0;
            }
            QPushButton:pressed {
                background-color: #0d47a1;
            }
        """)
        export_button.setFixedSize(100, 40)
        export_button.clicked.connect(self.export_to_pdf)
        
        # 删除选中行按钮
        delete_button = QPushButton("删除选中行")
        delete_button.setStyleSheet("""
            QPushButton {
                background-color: #dc3545;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 10px 20px;
                font-size: 14px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #c82333;
            }
            QPushButton:pressed {
                background-color: #bd2130;
            }
        """)
        delete_button.setFixedSize(120, 40)
        delete_button.clicked.connect(self.delete_selected_rows)
        
        # 导出Excel按钮
        export_excel_button = QPushButton("导出Excel")
        export_excel_button.setStyleSheet("""
            QPushButton {
                background-color: #28a745;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 10px 20px;
                font-size: 14px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #218838;
            }
            QPushButton:pressed {
                background-color: #1e7e34;
            }
        """)
        export_excel_button.setFixedSize(100, 40)
        export_excel_button.clicked.connect(self.export_to_excel)
        
        button_layout.addWidget(export_button)
        button_layout.addWidget(export_excel_button)
        button_layout.addWidget(delete_button)
        button_layout.addStretch()
        
        parent_layout.addLayout(button_layout)
        
    def create_table(self, parent_layout):
        """创建词汇表格"""
        self.table = QTableWidget()
        self.table.setStyleSheet("""
            QTableWidget {
                background-color: white;
                border: 1px solid #ddd;
                border-radius: 8px;
                gridline-color: #e0e0e0;
                selection-background-color: #e3f2fd;
                color: black;
            }
            QTableWidget::item {
                padding: 4px;
                color: black !important;
                background-color: transparent;
            }
            QTableWidget::item:selected {
                color: black !important;
                background-color: #e3f2fd;
            }
            QTableWidget::item:hover {
                color: black !important;
                background-color: rgba(227, 242, 253, 0.5);
            }
            QTableWidget::item:focus {
                color: black !important;
            }
            QTableWidget::item:selected:focus {
                color: black !important;
                background-color: #e3f2fd;
            }
            QHeaderView::section {
                background-color: #f8f9fa;
                padding: 3px;
                border: none;
                border-bottom: 2px solid #dee2e6;
                font-weight: bold;
                color: #495057;
            }
        """)
        
        # 设置表格列
        headers = ["单词", "词形转换", "小学", "初中", "高中", "示例句子", "示例句子2", "释义", "D1", "D2", "D4", "D7", "D15"]
        self.table.setColumnCount(len(headers))
        self.table.setHorizontalHeaderLabels(headers)
        
        # 设置列宽 - 允许手动调整
        header = self.table.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.ResizeMode.Interactive)  # 单词列 - 可调整
        header.setSectionResizeMode(1, QHeaderView.ResizeMode.Interactive)  # 词形转换列 - 可调整
        header.setSectionResizeMode(2, QHeaderView.ResizeMode.Interactive)  # 小学列 - 可调整
        header.setSectionResizeMode(3, QHeaderView.ResizeMode.Interactive)  # 初中列 - 可调整
        header.setSectionResizeMode(4, QHeaderView.ResizeMode.Interactive)  # 高中列 - 可调整
        header.setSectionResizeMode(5, QHeaderView.ResizeMode.Stretch)  # 示例句子列 - 自适应
        header.setSectionResizeMode(6, QHeaderView.ResizeMode.Stretch)  # 示例句子2列 - 可调整
        header.setSectionResizeMode(7, QHeaderView.ResizeMode.Interactive)  # 释义列 - 可调整
        self.table.setColumnWidth(0, 100)  # 单词列宽度
        self.table.setColumnWidth(1, 120)  # 词形转换列宽度
        self.table.setColumnWidth(2, 30)   # 小学列宽度
        self.table.setColumnWidth(3, 30)   # 初中列宽度
        self.table.setColumnWidth(4, 30)   # 高中列宽度
        self.table.setColumnWidth(7, 200)  # 释义列宽度
        
        # 设置D列宽度 - 允许手动调整
        for i in [8, 9, 10, 11, 12]:
            header.setSectionResizeMode(i, QHeaderView.ResizeMode.Interactive)
            self.table.setColumnWidth(i, 40)
        
        # 设置表格属性
        self.table.setAlternatingRowColors(True)
        self.table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        # 启用双击编辑
        self.table.setEditTriggers(QTableWidget.EditTrigger.DoubleClicked)
        
        # 设置行高以容纳两行示例句子
        self.table.verticalHeader().setDefaultSectionSize(46)
        
        # 启用行高调整
        self.table.verticalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Interactive)
        
        # 为示例句子列设置自定义委托
        self.table.setItemDelegateForColumn(5, WrapTextDelegate())
        
        # 禁用D列的双击编辑（现在使用单击切换对号）
        # 所有列都不可编辑
        editable_columns = []  # 不允许任何列双击编辑
        self.editable_delegate = EditableDelegate(editable_columns, self.table)
        self.table.setItemDelegate(self.editable_delegate)
        
        # 设置右键菜单
        self.table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.table.customContextMenuRequested.connect(self.show_context_menu)
        
        # 连接单元格点击事件
        self.table.cellClicked.connect(self.on_cell_clicked)
        
        parent_layout.addWidget(self.table)
        
    def on_cell_clicked(self, row, column):
        """处理单元格点击事件，D列切换对号"""
        # 检查是否点击的是D列（第8-12列）
        if column in [8, 9, 10, 11, 12]:
            item = self.table.item(row, column)
            if item:
                # 切换对号
                if item.text() == "✓":
                    item.setText("")
                else:
                    item.setText("✓")
            else:
                # 如果单元格不存在，创建一个新的
                new_item = QTableWidgetItem("✓")
                new_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                self.table.setItem(row, column, new_item)
            
            # 自动保存到 vocabulary.xlsx
            self.save_vocabulary_to_xlsx()
    
    def load_word_banks(self):
        """加载单词库文件"""
        word_bank_files = {
            '小学': '小学.txt',
            '初中': '初中.txt', 
            '高中': '高中.txt'
        }
        
        for level, filename in word_bank_files.items():
            try:
                if os.path.exists(filename):
                    with open(filename, 'r', encoding='utf-8') as f:
                        words = set()
                        for line in f:
                            word = line.strip().lower()
                            if word:
                                words.add(word)
                        self.word_banks[level] = words
                        print(f"加载{level}单词库: {len(words)}个单词")
                else:
                    print(f"单词库文件 {filename} 不存在")
                    self.word_banks[level] = set()
            except Exception as e:
                print(f"加载{level}单词库时出错: {e}")
                self.word_banks[level] = set()
                
    def get_word_levels(self, word):
        """根据单词库判断单词难度等级，返回多个等级"""
        word_lower = word.lower()
        levels = []
        
        # 检查每个等级
        if word_lower in self.word_banks.get('小学', set()):
            levels.append('小学')
        if word_lower in self.word_banks.get('初中', set()):
            levels.append('初中')
        if word_lower in self.word_banks.get('高中', set()):
            levels.append('高中')
            
        return levels
        
    def load_vocabulary(self):
        """从Excel文件加载词汇（四列：单词、释义、例句1、例句2）"""
        try:
            # 默认Excel文件路径
            default_file = "vocabulary.xlsx"
            
            if not os.path.exists(default_file):
                # 如果默认文件不存在，表格为空
                self.table.setRowCount(0)
                return
            
            file_path = default_file
            
            # 使用openpyxl读取Excel文件
            from openpyxl import load_workbook
            
            wb = load_workbook(file_path)
            ws = wb.active
            
            # 读取数据（Excel可能有7列或12列）
            # 7列格式：单词、词形转换、例句1、例句2、示例句子2、释义1、释义2
            # 12列格式：单词、词形转换、例句1、例句2、示例句子2、释义1、释义2、D1、D2、D4、D7、D15
            vocabulary_data = []
            for row in ws.iter_rows(min_row=1, values_only=True):
                # 跳过空行
                if not any(row):
                    continue
                
                # 根据实际列数（包括空列）来判断文件格式
                # 注意：即使D列是空的，row的长度也应该包含这些列
                col_count = len(row)
                
                if col_count >= 12:
                    # 12列格式（包含D列的格式）
                    word = str(row[0]).strip() if row[0] else ""
                    word_forms = str(row[1]).strip() if len(row) > 1 and row[1] else ""
                    example1 = str(row[2]).strip() if len(row) > 2 and row[2] else ""
                    example2 = str(row[3]).strip() if len(row) > 3 and row[3] else ""
                    phrases = str(row[4]).strip() if len(row) > 4 and row[4] else ""
                    meaning1 = str(row[5]).strip() if len(row) > 5 and row[5] else ""
                    meaning2 = str(row[6]).strip() if len(row) > 6 and row[6] else ""
                    
                    # 读取D列数据（第8-12列，对应索引7-11）
                    d1 = str(row[7]).strip() if len(row) > 7 and row[7] else ""
                    d2 = str(row[8]).strip() if len(row) > 8 and row[8] else ""
                    d4 = str(row[9]).strip() if len(row) > 9 and row[9] else ""
                    d7 = str(row[10]).strip() if len(row) > 10 and row[10] else ""
                    d15 = str(row[11]).strip() if len(row) > 11 and row[11] else ""
                    
                    # 拼接释义
                    meaning = ""
                    if meaning1 and meaning2:
                        meaning = f"{meaning1} {meaning2}"
                    elif meaning1:
                        meaning = meaning1
                    elif meaning2:
                        meaning = meaning2
                else:
                    # 7列格式（原始格式）
                    word = str(row[0]).strip() if row[0] else ""
                    word_forms = str(row[1]).strip() if len(row) > 1 and row[1] else ""
                    example1 = str(row[2]).strip() if len(row) > 2 and row[2] else ""
                    example2 = str(row[3]).strip() if len(row) > 3 and row[3] else ""
                    phrases = str(row[4]).strip() if len(row) > 4 and row[4] else ""
                    meaning1 = str(row[5]).strip() if len(row) > 5 and row[5] else ""
                    meaning2 = str(row[6]).strip() if len(row) > 6 and row[6] else ""
                    
                    # 拼接释义
                    meaning = ""
                    if meaning1 and meaning2:
                        meaning = f"{meaning1} {meaning2}"
                    elif meaning1:
                        meaning = meaning1
                    elif meaning2:
                        meaning = meaning2
                    
                    # D列默认为空
                    d1 = d2 = d4 = d7 = d15 = ""
                
                if word:  # 只要有单词就添加
                    vocabulary_data.append((word, meaning, word_forms, example1, example2, phrases, d1, d2, d4, d7, d15))
            
            # 设置表格行数
            self.table.setRowCount(len(vocabulary_data))
            
            # 填充表格数据
            for row, (word, meaning, word_forms, example1, example2, phrases, d1, d2, d4, d7, d15) in enumerate(vocabulary_data):
                # 单词列
                word_item = QTableWidgetItem(word)
                word_item.setTextAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
                self.table.setItem(row, 0, word_item)
                
                # 词形转换列
                word_forms_item = QTableWidgetItem(word_forms)
                word_forms_item.setTextAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
                self.table.setItem(row, 1, word_forms_item)
                
                # 难度等级列（小学、初中、高中）
                levels = self.get_word_levels(word)
                
                # 小学列
                primary_item = QTableWidgetItem("✓" if "小学" in levels else "")
                primary_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                if "小学" in levels:
                    primary_item.setBackground(QColor(255, 255, 200))  # 浅黄色
                self.table.setItem(row, 2, primary_item)
                
                # 初中列
                middle_item = QTableWidgetItem("✓" if "初中" in levels else "")
                middle_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                if "初中" in levels:
                    middle_item.setBackground(QColor(200, 255, 200))  # 浅绿色
                self.table.setItem(row, 3, middle_item)
                
                # 高中列
                high_item = QTableWidgetItem("✓" if "高中" in levels else "")
                high_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                if "高中" in levels:
                    high_item.setBackground(QColor(200, 200, 255))  # 浅蓝色
                self.table.setItem(row, 4, high_item)
                
                # 示例句子列（合并两个句子）
                combined_examples = ""
                if example1 and example2:
                    combined_examples = f"1. {example1}\n2. {example2}"
                elif example1:
                    combined_examples = f"1. {example1}"
                elif example2:
                    combined_examples = f"1. {example2}"
                
                example_item = QTableWidgetItem(combined_examples)
                example_item.setTextAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
                # 设置示例句子列的换行模式
                example_item.setData(Qt.ItemDataRole.UserRole, "wrap")
                self.table.setItem(row, 5, example_item)
                
                # 示例句子2列
                phrases_item = QTableWidgetItem(phrases)
                phrases_item.setTextAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
                self.table.setItem(row, 6, phrases_item)
                
                # 释义列
                meaning_item = QTableWidgetItem(meaning)
                meaning_item.setTextAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
                self.table.setItem(row, 7, meaning_item)
                
                # D列填充（从Excel读取的数据）
                d_values = [d1, d2, d4, d7, d15]
                for col, d_value in zip([8, 9, 10, 11, 12], d_values):
                    d_item = QTableWidgetItem(d_value)
                    d_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                    self.table.setItem(row, col, d_item)
                    
        except ImportError:
            QMessageBox.warning(self, "错误", "需要安装openpyxl库才能读取Excel文件。\n请运行: pip install openpyxl")
            self.table.setRowCount(0)
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载Excel文件时出错:\n{str(e)}")
            self.table.setRowCount(0)
    
    def save_vocabulary_to_xlsx(self):
        """保存当前表格数据到vocabulary.xlsx文件"""
        try:
            from openpyxl import Workbook
            import tempfile
            import shutil
            
            file_path = "vocabulary.xlsx"
            
            # 创建Excel工作簿
            wb = Workbook()
            ws = wb.active
            ws.title = "词汇表"
            
            # 写入数据（12列格式：单词、词形转换、例句1、例句2、示例句子2、释义1、释义2、D1、D2、D4、D7、D15）
            # 前7列是原始格式，第8-12列是D1-D15
            for row in range(self.table.rowCount()):
                word_item = self.table.item(row, 0)
                word_forms_item = self.table.item(row, 1)
                example_item = self.table.item(row, 5)  # 合并的示例句子
                phrases_item = self.table.item(row, 6)
                meaning_item = self.table.item(row, 7)
                d1_item = self.table.item(row, 8)
                d2_item = self.table.item(row, 9)
                d4_item = self.table.item(row, 10)
                d7_item = self.table.item(row, 11)
                d15_item = self.table.item(row, 12)
                
                if word_item:
                    # 分离示例句子为两个句子
                    examples_text = example_item.text() if example_item else ""
                    example1 = ""
                    example2 = ""
                    if '\n' in examples_text:
                        parts = examples_text.split('\n', 1)
                        example1 = parts[0][3:] if parts[0].startswith('1. ') else parts[0]
                        example2 = parts[1][3:] if parts[1].startswith('2. ') else parts[1]
                    elif examples_text:
                        example1 = examples_text[3:] if examples_text.startswith('1. ') else examples_text
                    
                    # 分离释义为两列（如果有空格，按第一个空格分割）
                    meaning_text = meaning_item.text() if meaning_item else ""
                    meaning1 = meaning_text
                    meaning2 = ""
                    
                    # 写入12列数据
                    ws.cell(row=row + 1, column=1, value=word_item.text() if word_item else "")
                    ws.cell(row=row + 1, column=2, value=word_forms_item.text() if word_forms_item else "")
                    ws.cell(row=row + 1, column=3, value=example1)
                    ws.cell(row=row + 1, column=4, value=example2)
                    ws.cell(row=row + 1, column=5, value=phrases_item.text() if phrases_item else "")
                    ws.cell(row=row + 1, column=6, value=meaning1)
                    ws.cell(row=row + 1, column=7, value=meaning2)
                    ws.cell(row=row + 1, column=8, value=d1_item.text() if d1_item else "")
                    ws.cell(row=row + 1, column=9, value=d2_item.text() if d2_item else "")
                    ws.cell(row=row + 1, column=10, value=d4_item.text() if d4_item else "")
                    ws.cell(row=row + 1, column=11, value=d7_item.text() if d7_item else "")
                    ws.cell(row=row + 1, column=12, value=d15_item.text() if d15_item else "")
            
            # 使用临时文件保存，然后替换原文件
            try:
                # 先保存到临时文件
                temp_fd, temp_path = tempfile.mkstemp(suffix='.xlsx', dir='.')
                os.close(temp_fd)  # 关闭文件描述符
                
                wb.save(temp_path)
                
                # 尝试替换原文件
                if os.path.exists(file_path):
                    try:
                        os.remove(file_path)
                    except PermissionError:
                        # 如果无法删除，尝试重命名为备份
                        backup_path = file_path + '.backup'
                        if os.path.exists(backup_path):
                            os.remove(backup_path)
                        os.rename(file_path, backup_path)
                
                shutil.move(temp_path, file_path)
                print(f"已自动保存到 {file_path}")
                
            except PermissionError as pe:
                # 如果临时文件存在，清理它
                if os.path.exists(temp_path):
                    try:
                        os.remove(temp_path)
                    except:
                        pass
                raise PermissionError(f"无法保存文件，请确保 {file_path} 没有被其他程序（如Excel）打开")
            
        except PermissionError as pe:
            print(f"保存失败: {str(pe)}")
            QMessageBox.warning(self, "保存失败", 
                f"无法保存到 vocabulary.xlsx\n\n"
                f"可能原因：\n"
                f"1. 文件正在被Excel或其他程序打开\n"
                f"2. 文件权限不足\n\n"
                f"请关闭所有打开该文件的程序后重试。")
        except Exception as e:
            print(f"保存vocabulary.xlsx时出错: {str(e)}")
            QMessageBox.warning(self, "保存失败", f"保存时出错:\n{str(e)}")
                
    def export_to_pdf(self):
        """导出表格为PDF文件"""
        try:
            # 获取保存文件路径
            file_path, _ = QFileDialog.getSaveFileName(
                self, 
                "导出PDF文件", 
                "词汇表.pdf", 
                "PDF文件 (*.pdf)"
            )
            
            if not file_path:
                return
                
            # 创建PDF文档
            doc = QTextDocument()
            
            # 构建HTML内容
            html_content = self.generate_html_content()
            doc.setHtml(html_content)
            
            # 创建打印机
            printer = QPrinter()
            printer.setOutputFormat(QPrinter.OutputFormat.PdfFormat)
            printer.setOutputFileName(file_path)
            # 使用简单的页面设置
            printer.setPageSize(QPageSize(QPageSize.PageSizeId.A4))
            printer.setPageMargins(QMarginsF(20, 20, 20, 20))
            # 设置横向打印（90度旋转）
            printer.setPageOrientation(QPageLayout.Orientation.Landscape) 
            
            # 打印到PDF
            doc.print(printer)
            
            QMessageBox.information(self, "成功", f"PDF文件已保存到:\n{file_path}")
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"导出PDF时出错:\n{str(e)}")
            
    def generate_html_content(self):
        """生成HTML内容用于PDF导出"""
        html = """
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>词汇表</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 20px; }
                h1 { text-align: center; color: #333; margin-bottom: 30px; }
                table { 
                    width: 100%; 
                    border-collapse: collapse; 
                    margin-top: 20px;
                    border: 2px solid #333;
                }
                th, td { 
                    border: 1px solid #333; 
                    padding: 6px; 
                    text-align: left;
                    vertical-align: top;
                }
                th { 
                    background-color: #f8f9fa; 
                    font-weight: bold;
                    border: 1px solid #333;
                }
                .primary { background-color: #fff3cd; }
                .middle { background-color: #d4edda; }
                .high { background-color: #cce5ff; }
                .checkmark { text-align: center; font-weight: bold; }
                tr:nth-child(even) { background-color: #f9f9f9; }
            </style>
        </head>
        <body>
            <h1>Ebbinghaus Vocabulary List</h1>
            <table>
                <thead>
                    <tr>
                        <th>单词</th>
                        <th>词形转换</th>
                        <th>小学</th>
                        <th>初中</th>
                        <th>高中</th>
                        <th>示例句子</th>
                        <th>示例句子2</th>
                        <th>释义</th>
                        <th>D1</th>
                        <th>D2</th>
                        <th>D4</th>
                        <th>D7</th>
                        <th>D15</th>
                    </tr>
                </thead>
                <tbody>
        """
        
        # 添加表格数据
        for row in range(self.table.rowCount()):
            html += "<tr>"
            for col in range(self.table.columnCount()):
                item = self.table.item(row, col)
                text = item.text() if item else ""
                
                # 根据列设置样式
                if col == 2:  # 小学列
                    if text == "✓":
                        html += f'<td class="primary checkmark" style="border: 1px solid #333;">{text}</td>'
                    else:
                        html += f'<td class="checkmark" style="border: 1px solid #333;">{text}</td>'
                elif col == 3:  # 初中列
                    if text == "✓":
                        html += f'<td class="middle checkmark" style="border: 1px solid #333;">{text}</td>'
                    else:
                        html += f'<td class="checkmark" style="border: 1px solid #333;">{text}</td>'
                elif col == 4:  # 高中列
                    if text == "✓":
                        html += f'<td class="high checkmark" style="border: 1px solid #333;">{text}</td>'
                    else:
                        html += f'<td class="checkmark" style="border: 1px solid #333;">{text}</td>'
                elif col in [8, 9, 10, 11, 12]:  # D列
                    html += f'<td style="text-align: center; border: 1px solid #333;">{text}</td>'
                else:
                    html += f'<td style="border: 1px solid #333;">{text}</td>'
            html += "</tr>"
        
        html += """
                </tbody>
            </table>
        </body>
        </html>
        """
        
        return html
        
    def delete_selected_rows(self):
        """删除选中的行"""
        selected_rows = set()
        for item in self.table.selectedItems():
            selected_rows.add(item.row())
        
        if not selected_rows:
            QMessageBox.warning(self, "警告", "请先选择要删除的行！")
            return
            
        # 确认删除
        reply = QMessageBox.question(
            self, 
            "确认删除", 
            f"确定要删除选中的 {len(selected_rows)} 行吗？\n此操作无法撤销！",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            # 按降序排列行号，避免删除时索引变化
            rows_to_delete = sorted(selected_rows, reverse=True)
            
            for row in rows_to_delete:
                self.table.removeRow(row)
            
            # 保存更新后的词汇文件
            self.save_vocabulary_to_file()
            # 同时保存到 vocabulary.xlsx
            self.save_vocabulary_to_xlsx()
            
            QMessageBox.information(self, "成功", f"已删除 {len(rows_to_delete)} 行")
    
    def save_vocabulary_to_file(self):
        """保存当前表格数据到词汇文件"""
        try:
            vocabulary_file = "vocabulary.txt"
            with open(vocabulary_file, 'w', encoding='utf-8') as f:
                for row in range(self.table.rowCount()):
                    word_item = self.table.item(row, 0)
                    word_forms_item = self.table.item(row, 1)  # 词形转换列
                    meaning_item = self.table.item(row, 7)  # 释义列
                    example_item = self.table.item(row, 5)   # 示例句子列
                    phrases_item = self.table.item(row, 6)   # 示例句子2列
                    
                    if word_item and meaning_item:
                        word = word_item.text()
                        word_forms = word_forms_item.text() if word_forms_item else ""
                        meaning = meaning_item.text()
                        examples_text = example_item.text() if example_item else ""
                        phrases = phrases_item.text() if phrases_item else ""
                        
                        # 分离两个示例句子并去除编号前缀
                        if '\n' in examples_text:
                            example1, example2 = examples_text.split('\n', 1)
                            # 去除编号前缀
                            example1 = example1[3:] if example1.startswith('1. ') else example1
                            example2 = example2[3:] if example2.startswith('2. ') else example2
                        else:
                            example1 = examples_text[3:] if examples_text.startswith('1. ') else examples_text
                            example2 = ""
                        
                        # 写入文件 - 新格式：单词#释义#词形转换#例句1#例句2#示例句子2
                        # 注意：这里保存的是拼接后的释义，如果需要拆分需要额外处理
                        line = f"{word}#{meaning}#{word_forms}#{example1}#{example2}#{phrases}"
                        
                        f.write(line + '\n')
            
            print(f"词汇文件已更新，共 {self.table.rowCount()} 行")
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"保存词汇文件时出错:\n{str(e)}")
    
    def show_context_menu(self, position):
        """显示右键菜单"""
        menu = QMenu(self)
        
        # 调整行高菜单
        row_height_menu = menu.addMenu("调整行高")
        
        # 预设行高选项
        heights = [30, 40, 50, 60, 70, 80]
        for height in heights:
            action = row_height_menu.addAction(f"{height}px")
            action.triggered.connect(lambda checked, h=height: self.set_row_height(h))
        
        # 自定义行高
        custom_action = row_height_menu.addAction("自定义...")
        custom_action.triggered.connect(self.set_custom_row_height)
        
        # 重置行高
        reset_action = menu.addAction("重置所有行高")
        reset_action.triggered.connect(self.reset_row_heights)
        
        # 调整列宽菜单
        col_width_menu = menu.addMenu("调整列宽")
        
        # 重置列宽
        reset_cols_action = col_width_menu.addAction("重置所有列宽")
        reset_cols_action.triggered.connect(self.reset_column_widths)
        
        # 自适应列宽
        auto_fit_action = col_width_menu.addAction("自适应列宽")
        auto_fit_action.triggered.connect(self.auto_fit_columns)
        
        menu.exec(self.table.mapToGlobal(position))
    
    def set_row_height(self, height):
        """设置选中行的行高"""
        selected_rows = set()
        for item in self.table.selectedItems():
            selected_rows.add(item.row())
        
        if selected_rows:
            for row in selected_rows:
                self.table.setRowHeight(row, height)
        else:
            # 如果没有选中行，设置所有行
            for row in range(self.table.rowCount()):
                self.table.setRowHeight(row, height)
    
    def set_custom_row_height(self):
        """设置自定义行高"""
        height, ok = QInputDialog.getInt(self, "设置行高", "请输入行高（像素）:", 46, 20, 200)
        if ok:
            self.set_row_height(height)
    
    def reset_row_heights(self):
        """重置所有行高"""
        for row in range(self.table.rowCount()):
            self.table.setRowHeight(row, 46)
    
    def reset_column_widths(self):
        """重置所有列宽"""
        self.table.setColumnWidth(0, 100)  # 单词列
        self.table.setColumnWidth(1, 120)  # 词形转换列
        self.table.setColumnWidth(2, 30)   # 小学列
        self.table.setColumnWidth(3, 30)   # 初中列
        self.table.setColumnWidth(4, 30)   # 高中列
        self.table.setColumnWidth(7, 200)  # 释义列
        for i in [8, 9, 10, 11, 12]:
            self.table.setColumnWidth(i, 40)  # D列
    
    def auto_fit_columns(self):
        """自适应列宽"""
        self.table.resizeColumnsToContents()
        # 限制最小宽度
        for col in range(self.table.columnCount()):
            current_width = self.table.columnWidth(col)
            if current_width < 30:
                self.table.setColumnWidth(col, 30)
    
    def export_to_excel(self):
        """导出表格数据到Excel文件"""
        try:
            # 选择保存路径
            file_path, _ = QFileDialog.getSaveFileName(
                self, 
                "导出Excel文件", 
                "词汇表.xlsx", 
                "Excel文件 (*.xlsx);;所有文件 (*)"
            )
            
            if not file_path:
                return
            
            # 确保文件扩展名
            if not file_path.endswith('.xlsx'):
                file_path += '.xlsx'
            
            # 创建Excel工作簿
            from openpyxl import Workbook
            from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
            from openpyxl.utils import get_column_letter
            
            wb = Workbook()
            ws = wb.active
            ws.title = "词汇表"
            
            # 设置表头
            headers = ["单词", "词形转换", "小学", "初中", "高中", "示例句子", "示例句子2", "释义", "D1", "D2", "D4", "D7", "D15"]
            for col, header in enumerate(headers, 1):
                cell = ws.cell(row=1, column=col, value=header)
                cell.font = Font(bold=True, color="FFFFFF")
                cell.fill = PatternFill(start_color="366092", end_color="366092", fill_type="solid")
                cell.alignment = Alignment(horizontal="center", vertical="center")
            
            # 填充数据
            for row in range(self.table.rowCount()):
                for col in range(self.table.columnCount()):
                    item = self.table.item(row, col)
                    if item:
                        cell_value = item.text()
                        cell = ws.cell(row=row + 2, column=col + 1, value=cell_value)
                        
                        # 设置单元格样式
                        cell.alignment = Alignment(horizontal="left", vertical="center", wrap_text=True)
                        
                        # 根据列设置特殊样式
                        if col == 0:  # 单词列
                            cell.font = Font(bold=True)
                        elif col in [2, 3, 4]:  # 小学、初中、高中列
                            if cell_value == "✓":
                                cell.fill = PatternFill(start_color="FFFF00", end_color="FFFF00", fill_type="solid")
                            cell.alignment = Alignment(horizontal="center", vertical="center")
                        elif col == 5:  # 示例句子列
                            cell.alignment = Alignment(horizontal="left", vertical="top", wrap_text=True)
                        elif col == 7:  # 释义列
                            cell.alignment = Alignment(horizontal="left", vertical="center", wrap_text=True)
                        elif col in [8, 9, 10, 11, 12]:  # D列
                            cell.alignment = Alignment(horizontal="center", vertical="center")
            
            # 设置列宽
            column_widths = [12, 15, 6, 6, 6, 40, 20, 30, 6, 6, 6, 6, 6]
            for i, width in enumerate(column_widths, 1):
                ws.column_dimensions[get_column_letter(i)].width = width
            
            # 设置行高
            for row in range(2, self.table.rowCount() + 2):
                ws.row_dimensions[row].height = 30
            
            # 添加边框
            thin_border = Border(
                left=Side(style='thin'),
                right=Side(style='thin'),
                top=Side(style='thin'),
                bottom=Side(style='thin')
            )
            
            for row in ws.iter_rows(min_row=1, max_row=self.table.rowCount() + 1):
                for cell in row:
                    cell.border = thin_border
            
            # 保存文件
            wb.save(file_path)
            
            QMessageBox.information(self, "成功", f"Excel文件已导出到:\n{file_path}")
            
        except ImportError:
            QMessageBox.warning(self, "错误", "需要安装openpyxl库才能导出Excel文件。\n请运行: pip install openpyxl")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"导出Excel时出错:\n{str(e)}")

def main():
    app = QApplication(sys.argv)
    
    # 设置应用程序样式
    app.setStyle('Fusion')
    
    window = EbbinghausVocabularyApp()
    window.show()
    
    sys.exit(app.exec())

if __name__ == '__main__':
    main()
